package com.iyang.boothbaseapitest.config;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author: Mu_YI
 * @Date: 2019/3/13 22:00
 * @Version 1.0
 */
public class HBaseConn {

    private static final Logger LOGGER = LoggerFactory.getLogger(HBaseConn.class);

    private static final HBaseConn INSTANCE = new HBaseConn();
    private static Configuration configuration;
    private static Connection connection;

    private HBaseConn(){
        try{
            if(configuration == null){
                configuration = HBaseConfiguration.create();
                configuration.set("hbase.zookeeper.quorum","192.168.119.129:2181");
            }
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
        }
    }

    private Connection getConnection(){
        if(connection == null || connection.isClosed()){
            try{
                connection = ConnectionFactory.createConnection(configuration);
            }catch (Exception e){
                LOGGER.error(e.getMessage(),e);
            }
        }
        return connection;
    }

    public static Connection getHBaseConn(){
        return INSTANCE.getConnection();
    }

    public static Table getTable(String tableName) throws  Exception{
        return INSTANCE.getConnection().getTable(TableName.valueOf(tableName));
    }

    public static void closeConn(){
        if(connection != null){
            try{
                connection.close();
            }catch (Exception e){
                LOGGER.error(e.getMessage(),e);
            }
        }
    }
}
